<template>
  <div class="container">
    <div class="tabber">
      <a-space size="medium" direction="vertical" fill>
        <a-space>
          <a-input
            placeholder="请输入订单号进行搜索"
            v-model="search"
          ></a-input>
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <icon-search />
            </template>
            <template #default>搜索</template>
          </a-button>
          <a-select
            @change="handleToggle"
            style="width: 100px"
            v-model="searchType"
          >
            <a-option :value="-2">全部</a-option>
            <a-option :value="-1">已取消</a-option>
            <a-option :value="0">未支付</a-option>
            <a-option :value="1">已支付</a-option>
            <a-option :value="2">已发货</a-option>
            <a-option :value="3">已完成</a-option>
            <a-option :value="4">已退款</a-option>
          </a-select>
        </a-space>
        <a-space>
          <a-button type="primary" @click="handleRefresh">
            <template #icon>
              <icon-loop />
            </template>
            <template #default>刷新</template>
          </a-button>
          <a-button
            status="danger"
            @click="deleteAll = selectedKeys.length > 0 ? true : false"
          >
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-space>
      </a-space>
    </div>
    <a-table
      row-key="id"
      :columns="columns"
      :data="data"
      column-resizable
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      :bordered="{ cell: true }"
      :scroll="{ x: 'min-content' }"
      size="small"
      :table-layout-fixed="true"
    >
      <template #user="{ record }">
        #{{ record.user.id }} {{ record.user.nikeName }}
      </template>
      <template #totalAmount="{ record }">
        ¥{{
          record.totalAmount
            ? parseFloat(record.totalAmount).toFixed(2)
            : "0.00"
        }}
      </template>
      <template #status="{ record }">
        <template v-if="record.status == -1">
          <a-tag color="gray">已取消</a-tag>
        </template>
        <template v-if="record.status == 0">
          <a-tag color="pinkpurple">未支付</a-tag>
        </template>
        <template v-if="record.status == 1">
          <a-tag color="green">已支付</a-tag>
        </template>
        <template v-if="record.status == 2">
          <a-tag color="orange">已发货</a-tag>
        </template>
        <template v-if="record.status == 3">
          <a-tag color="blue">已完成</a-tag>
        </template>
        <template v-if="record.status == 4">
          <a-tag color="red">已退款</a-tag>
        </template>
      </template>
      <template #isRefund="{ record }">
        <template v-if="record.isRefund && record.status != 4">
          <a-popconfirm
            @ok="refundHanddle(record.id, false)"
            content="是否拒绝退款?"
          >
            <a-button status="danger" size="mini" style="margin-right: 10px"
              >拒绝
            </a-button>
          </a-popconfirm>
          <a-popconfirm
            @ok="refundHanddle(record.id, true)"
            content="是否同意退款?"
          >
            <a-button status="success" size="mini">同意 </a-button>
          </a-popconfirm>
        </template>
        <template v-else>
          <a-tag color="gray">否</a-tag>
        </template>
      </template>
      <template #createdAt="{ record }">
        {{ formatTime(record.createdAt) }}
      </template>
      <template #optional="{ record }">
        <a-button
          v-if="record.status == 1"
          size="mini"
          status="warning"
          style="margin-right: 5px"
          @click="
            shipmentsButton(record);
            isEditShipments = true;
          "
          >发货</a-button
        >
        <a-button
          v-if="record.status == 2"
          size="mini"
          status=""
          style="margin-right: 5px"
          @click="
            shipmentsButton(record);
            isEditShipments = true;
          "
          >修改</a-button
        >
        <a-button
          v-if="record.express && record.status != 2"
          size="mini"
          status=""
          style="margin-right: 5px"
          @click="
            shipmentsButton(record);
            isEditShipments = false;
          "
          >物流</a-button
        >
        <a-button
          size="mini"
          status="primary"
          style="margin-right: 5px"
          @click="editorHanddle(record)"
          >编辑</a-button
        >
        <a-button size="mini" status="danger" @click="deleteHanddle(record)"
          >删除</a-button
        >
      </template>
      <template #items="{ record }">
        <div style="display: flex; justify-content: center">
          <div style="margin-right: 10px">
            共
            <span style="width: 10px; display: inline-block">{{
              record.items.length
            }}</span>
            件
          </div>
          <a-button
            @click="
              showGoods = true;
              goodsData = record.items;
            "
            type="primary"
            status="success"
            size="mini"
            >查看</a-button
          >
        </div>
      </template>
      <template #address="{ record }">
        <div style="font-size: 12px">
          <div>{{ record.address.name }} {{ record.address.phone }}</div>
          <div>城市：{{ record.address.region }}</div>
          <div>详细：{{ record.address.site }}</div>
        </div>
      </template>
    </a-table>
  </div>
  <!-- 编辑弹框 -->
  <a-modal
    v-model:visible="visible"
    :title="isAdd ? '添加数据' : '修改数据'"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <!-- <a-typography-text type="secondary" style="margin-left: 10vh;margin-bottom: 10px;">id:{{ form.id
          }}</a-typography-text> -->
    <a-form :model="form" style="padding-right: 40px">
      <a-form-item label="ID" v-if="!isAdd">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item label="用户ID">
        <a-space direction="vertical" v-if="form.user">
          <a-space
            >#id &nbsp;<a-input disabled v-model="form.user.id" />
          </a-space>
          <a-space
            >用户<a-input disabled v-model="form.user.nikeName" />
          </a-space>
        </a-space>
      </a-form-item>
      <a-form-item label="支付金额">
        <a-input-number
          :disabled="form.status !== 0"
          v-model="form.totalAmount"
          :style="{ width: '180px' }"
          :precision="2"
          mode="button"
          size="large"
          class="input-demo"
        />
      </a-form-item>
      <a-form-item label="下单方式">
        <a-select v-model="form.method" disabled placeholder="请选择类型">
          <a-option>余额</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="订单状态" v-if="!isAdd">
        <a-select v-model="form.status" disabled>
          <a-option :value="-1">已取消</a-option>
          <a-option :value="0">未支付</a-option>
          <a-option :value="1">已支付</a-option>
          <a-option :value="2">已发货</a-option>
          <a-option :value="3">已完成</a-option>
          <a-option :value="4">已退款</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="收货人" v-if="form.address">
        <a-input v-model="form.address.name" placeholder="手机号码" />
      </a-form-item>
      <a-form-item label="手机号码" v-if="form.address">
        <a-input v-model="form.address.phone" placeholder="手机号码" />
      </a-form-item>
      <a-form-item label="地区" v-if="form.address">
        <a-input v-model="form.address.region" placeholder="手机号码" />
      </a-form-item>
      <a-form-item label="详情地址" v-if="form.address">
        <a-input v-model="form.address.site" placeholder="手机号码" />
      </a-form-item>
      <a-form-item label="邮编" v-if="form.address">
        <a-input v-model="form.address.postcode" placeholder="手机号码" />
      </a-form-item>

      <a-form-item label="备注">
        <a-textarea
          :auto-size="{ minRows: 4, maxRows: 6 }"
          placeholder="暂无备注"
          v-model="form.notes"
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除弹框 -->
  <a-modal v-model:visible="delvalue" title="确认删除" @before-ok="delBeforeOk">
    <a-form :model="form">
      <a-form-item field="id" label="ID">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item field="name" label="作者">
        <a-input disabled :placeholder="form.user?.nikeName" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除已选的 -->
  <a-modal v-model:visible="deleteAll" @before-ok="handleDeleteAll">
    <template #title> 警告 </template>
    <div>是否删除已选 {{ selectedKeys.length }} 项数据？</div>
  </a-modal>
  <!-- 查看下单商品弹框 -->
  <a-modal v-model:visible="showGoods" title="下单的商品" width="600px">
    <div style="padding-bottom: 10px">共{{ goodsData.length }}件</div>
    <a-list>
      <a-list-item v-for="item in goodsData" :key="item.id">
        <a-list-item-meta
          :title="item.store.title"
          :description="
            'id:' +
            item.id +
            ' ｜单价：¥' +
            item.price +
            ' ｜数量：' +
            item.quantity +
            ' ｜总价：¥' +
            item.total
          "
        >
          <template #avatar>
            <a-avatar shape="square">
              <img alt="avatar" :src="BASE_URL + item.store.covers[0]" />
            </a-avatar>
          </template>
        </a-list-item-meta>
      </a-list-item>
    </a-list>
  </a-modal>
  <!-- 查看发货商品弹框 -->
  <a-modal
    v-model:visible="showShipments"
    @before-ok="shipmentsHanddle"
    title="下单的商品"
    width="600px"
  >
    <a-space direction="vertical">
      <div>共{{ form.items?.length }}件</div>
      <a-list>
        <a-list-item v-for="item in form.items" :key="item.id">
          <a-list-item-meta
            :title="item.store.title"
            :description="
              'id:' +
              item.id +
              ' ｜单价：¥' +
              item.price +
              ' ｜数量：' +
              item.quantity +
              ' ｜总价：¥' +
              item.total
            "
          >
            <template #avatar>
              <a-avatar shape="square">
                <img alt="avatar" :src="BASE_URL + item.store.covers[0]" />
              </a-avatar>
            </template>
          </a-list-item-meta>
        </a-list-item>
      </a-list>
      <a-space>
        <a-select
          v-model="form.express"
          :style="{ width: '120px' }"
          placeholder="请选择"
          :disabled="!isEditShipments"
        >
          <a-option>顺丰快递</a-option>
          <a-option>中通快递</a-option>
          <a-option>申通快递</a-option>
          <a-option>圆通快递</a-option>
          <a-option>韵达快递</a-option>
          <a-option>邮政EMS</a-option>
          <a-option>百世快递</a-option>
          <a-option>极兔快递</a-option>
        </a-select>
        <a-input
          v-model="form.tracking"
          allow-clear
          placeholder="请输入快递订单号"
          :disabled="!isEditShipments"
        >
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-space>
    </a-space>
  </a-modal>
</template>

<script setup>
import { BASE_URL } from "../../constant/index";
import { reactive, ref, onMounted } from "vue";
import { formatTime } from "../../utils/dataUtils";
import {
  getOrderListApi,
  postOrderDeliverApi,
  postOrderRefundOkApi,
  postOrderRefundNoApi,
  deleteOrderApi,
  putOrderApi,
} from "../../api/store.js";
import {
  IconPlus,
  IconSearch,
  IconLoop,
  IconDelete,
  IconUser,
} from "@arco-design/web-vue/es/icon";

import { Message } from "@arco-design/web-vue";

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: false,
  onlyCurrent: false,
});
const pagination = { pageSize: 10 };
const columns = [
  {
    title: "id",
    dataIndex: "id",
    fixed: "left",
    width: 150,
    ellipsis: true,
    tooltip: true,
    align: "center",
  },
  {
    title: "下单用户",
    slotName: "user",
    ellipsis: true,
    tooltip: true,
    width: 220,
    align: "center",
  },
  {
    title: "支付金额",
    slotName: "totalAmount",
    ellipsis: true,
    tooltip: true,
    width: 140,
    align: "center",
  },
  {
    title: "下单方式",
    dataIndex: "method",
    ellipsis: true,
    tooltip: true,
    width: 100,
    align: "center",
  },
  {
    title: "订单状态",
    slotName: "status",
    ellipsis: true,
    tooltip: true,
    width: 100,
    align: "center",
  },
  {
    title: "申请退货",
    slotName: "isRefund",
    ellipsis: true,
    tooltip: true,
    width: 140,
    align: "center",
  },

  {
    title: "下单商品",
    slotName: "items",
    ellipsis: true,
    tooltip: true,
    width: 150,
    align: "center",
  },
  {
    title: "收货地址",
    slotName: "address",
    ellipsis: true,
    tooltip: true,
    width: 250,
    // align: "center",
  },
  {
    title: "备注",
    dataIndex: "notes",
    ellipsis: true,
    tooltip: true,
    width: 120,
    align: "center",
  },
  {
    title: "创建时间",
    slotName: "createdAt",
    width: 220,
    align: "center",
  },
  {
    title: "操作",
    fixed: "right",
    width: 200,
    slotName: "optional",
    align: "center",
  },
];

const data = ref([]);

const topicList = ref([]);

// 获取所有数据
async function getListData() {
  const getRes = await getOrderListApi({
    limit: 1000,
    page: 1,
  });
  console.log(getRes.data.list);
  if (getRes.code === 200) {
    const list = getRes.data.list.map((item) => {
      return {
        ...item,
        totalAmount: Number(item.totalAmount),
        createdAt: formatTime(item.createdAt),
        updatedAt: formatTime(item.updatedAt),
      };
    });
    data.value = list;
  }
}

// 获取用户数据
onMounted(() => {
  getListData();
});

// 显示商品列表
const showGoods = ref(false);
// 商品列表数据
const goodsData = ref([]);

//切换分类函数
async function handleToggle(type) {
  search.value = "";
  await getListData();
  if (type !== -2) {
    data.value = data.value.filter((item) => {
      return item.status === type;
    });
  }
}

// 点击刷新按钮
function handleRefresh() {
  data.value = [];
  getListData();
}
const deleteAll = ref(false);
// 已选择的数据
const selectedKeys = ref([]);
// 点击删除按钮
async function handleDeleteAll(done) {
  console.log(selectedKeys.value);
  const pra = selectedKeys.value.map((id) => {
    return new Promise(async (resolve, reject) => {
      const delRes = await deleteOrderApi({ id });
      console.log(delRes);
      if (delRes.code === 200) {
        resolve(delRes);
      } else {
        reject(delRes);
      }
    });
  });
  try {
    await Promise.all(pra);
    Message.success("批量删除成功");
    done();
    getListData();
  } catch (err) {
    Message.error("批量删除失败");
  }
  console.log("结束");

  return false;
}

const searchType = ref(-2);
const search = ref("");
async function handleSearch() {
  await getListData();
  searchType.value = -2;
  data.value = data.value.filter((item) => {
    return item.id.includes(search.value);
  });
}
// 上传图片回调
function onUploadSuccess(res) {
  console.log(res.response);
  if (res.response.code === 200) {
    const atlas = res.response.data[0];
    if (form.value.atlas == undefined) {
      form.value.atlas = [];
    }
    form.value.atlas.push(atlas);
  }
}
// 删除图片验证
function beforeRemove(file) {
  console.log(file);
  form.value.atlas = form.value.atlas.filter(
    (item) => "http://127.0.0.1:3000" + item != file.url
  );

  console.log(form.value.atlas);
  return true;
}
// 删除视频验证
function beforeVideoRemove(file) {
  form.value.videoUrl = "";
  return true;
}
// 上传视频回调
function onUploadVideoSuccess(res) {
  console.log(res.response);
  if (res.response.code === 200) {
    const videoUrl = res.response.data[0];
    form.value.videoUrl = videoUrl;
  }
}

// 显示编辑弹框
const visible = ref(false);
const form = ref({});
const isAdd = ref(false);
// 取消弹框
function handleCancel() {
  isAdd.value = false;
  form.value = {};
}
// 点击编辑按钮
function editorHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  //   form.value = item;
  visible.value = true;
}
// 确认修改按钮
async function handleBeforeOk(done) {
  if (isAdd.value) {
    await handleAdd(done);
  } else {
    await handleUpdate(done);
  }
  // form.value = {};
  return false;
}
// 验证上传文件是否是视频
function beforeUpload(file) {
  return new Promise((resolve, reject) => {
    if (file.type.indexOf("video") === -1) {
      Message.error("上传文件必须为视频格式");
      reject(false);
    } else {
      resolve(true);
    }
  });
}
// 新增逻辑
async function handleAdd(done) {
  console.log(form.value);
  const {
    desc,
    type,
    atlas,
    videoUrl,
    videoCover,
    address,
    topics = [],
    isShow,
  } = form.value;

  if (!desc) {
    Message.error("请输入正文");
    return false;
  }
  console.log(isShow);
  if (isShow === undefined) {
    Message.error("请选择状态");
    return false;
  }
  if (type == 2) {
    if (!videoUrl) {
      Message.error("视频地址不能为空");
      return false;
    }
  }
  console.log(topics);
  // 获取话题id
  const topicId = [];
  for (let i = 0; i < topics.length; i++) {
    const element = topics[i];
    topicId.push(element.id);
  }
  const addRes = await addDynamicApi({
    desc,
    type,
    atlas,
    videoUrl,
    videoCover,
    address,
    topicId,
    isShow,
  });
  console.log(addRes);
  if (addRes.code === 200) {
    Message.success("新增成功");
    await getListData();
    form.value = {};
    done();
  } else {
    console.log(postRes);
    Message.error(postRes.message);
    return false;
  }
}
// 更新逻辑
async function handleUpdate(done) {
  console.log(form.value);
  const { id, totalAmount, notes, address } = form.value;
  console.log(address);
  if (!id) {
    Message.error("id不能为空");
    return false;
  }

  if (totalAmount == undefined) {
    Message.error("请输入支付金额");
    return false;
  }
  if (totalAmount < 0) {
    Message.error("支付金额不能小于0");
    return false;
  }
  console.log(address.name);
  if (!address.name) {
    Message.error("收货人姓名不能为空");
    return false;
  }
  if (!address.phone) {
    Message.error("收货人电话不能为空");
    return false;
  }
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(address.phone)) {
    Message.error("请输入正确的手机号码");
    return false;
  }
  if (!address.region) {
    Message.error("收货地区不能为空");
    return false;
  }
  if (!address.site) {
    Message.error("详细收货地址不能为空");
  }

  const upRes = await putOrderApi({
    id,
    totalAmount,
    notes,
    address,
  });
  console.log(upRes);
  if (upRes.code == 200) {
    Message.success("修改成功");
    getListData();
    done();
  } else {
    Message.error("修改失败");
    return false;
  }
}

// 删除弹框
const delvalue = ref(false);
// 点击删除按钮
function deleteHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  delvalue.value = true;
}
// 确认删除
async function delBeforeOk() {
  const { id } = form.value;
  console.log(id);
  const delRes = await deleteOrderApi({ id });
  console.log(delRes);
  if (delRes.code === 200) {
    Message.info("删除成功");
    // 更新数据
    getListData();
    delvalue.value = false;
  } else {
    Message.error("删除失败");
    return false;
  }
}
// 发货按钮
const isEditShipments = ref(true);
const showShipments = ref(false);
function shipmentsButton(item) {
  form.value = JSON.parse(JSON.stringify(item));
  showShipments.value = true;
}
async function shipmentsHanddle(done) {
  console.log(form.value);
  const { express, tracking, id } = form.value;
  if (!express) {
    Message.error("请选择快递公司");
    return false;
  }
  if (tracking == "") {
    Message.error("请输入快递单号");
    return false;
  }
  const regex = /^[A-Za-z0-9]{10,20}$/;
  if (!regex.test(tracking)) {
    Message.error("请输入正确的快递单号");
    return false;
  }
  console.log(tracking, express);
  const postRes = await postOrderDeliverApi({
    orderId: id,
    express,
    tracking,
  });
  console.log(postRes);
  if (postRes.code == 200) {
    Message.success(postRes.message);
    getListData();
    done();
  } else {
    Message.error(postRes.message);
  }
  return false;
}

// 退款操作
async function refundHanddle(id, agree) {
  console.log(id, agree);
  Message;
  // 同意退款
  if (agree) {
    const postRes = await postOrderRefundOkApi({ orderId: id });
    console.log(postRes);
    if (postRes.code == 200) {
      Message.success("已同意退款");
    } else {
      Message.error("同意退款失败");
    }
    getListData();
  }
  // 拒绝退款
  else {
    const postRes = await postOrderRefundNoApi({ orderId: id });
    console.log(postRes);
    if (postRes.code == 200) {
      Message.success("已拒绝退款");
    } else {
      Message.error("拒绝退款失败");
    }
    getListData();
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 14px;
  box-sizing: border-box;
  .tabber {
    padding-bottom: 14px;
  }
}
.container :deep(td) {
  // display: flex;
  // align-items: center;
  vertical-align: middle;
}
.topic-item {
  // background-color: red;
  padding: 4px 14px;
  // border-radius: 4px;
  &:hover {
    background-color: #f2f3f5;
    cursor: pointer;
  }
}
</style>
